/*
 * wptextbrowser.cpp
 *
 *  Created on: 2.12.2009
 *      Author: jkal
 */

#include <QKeyEvent>
#include <QScrollBar>

#include <QDebug>

#include "wptextbrowser.h"
#include "wpscrollarea.h"

WPTextBrowser::WPTextBrowser(QWidget *aParent) : QTextBrowser(aParent), mousePressed(false)
{
}

WPTextBrowser::~WPTextBrowser()
{
}

void WPTextBrowser::mousePressEvent(QMouseEvent *ev)
{
    mousePressed = true;
    lastMousePoint = ev->pos();
}

void WPTextBrowser::mouseMoveEvent(QMouseEvent *ev)
{
    if (mousePressed) {
        QPoint diff = lastMousePoint - ev->pos();
        QScrollBar *bar = verticalScrollBar();
        if (!bar)
            return;

        int newPos = bar->value() + diff.y();
        if (newPos < bar->minimum())
            newPos = bar->minimum();
        else if (newPos > bar->maximum())
            newPos = bar->maximum();
        bar->setValue(newPos);
        lastMousePoint = ev->pos();
    }
}

void WPTextBrowser::mouseReleaseEvent(QMouseEvent *ev)
{
    mousePressed = false;
}

void WPTextBrowser::keyPressEvent(QKeyEvent *e)
{
#ifdef QT_KEYPAD_NAVIGATION
    if (e->key() == Qt::Key_Up)
    {
    	// First we check if we need to scroll the area. If not, then we need to inform
    	// parent scroll area that the next widget should be focused.
    	QScrollBar* scrollBar = verticalScrollBar();
    	if (iScrollArea && (!scrollBar || scrollBar->value() == scrollBar->minimum()))
            iScrollArea->HandleScrollEvent(e);
    	else if (scrollBar) // If no scrollbar, do nothing (a programming error has occured)
    	{
            // Calling setEditFocus(true) enables keyboard scrolling in QTextBrowser.
            setEditFocus(true);
            QTextBrowser::keyPressEvent(e);
    	}
    }
    if (e->key() == Qt::Key_Down)
    {
    	QScrollBar* scrollBar = verticalScrollBar();
    	if (iScrollArea && (!scrollBar || scrollBar->value() == scrollBar->maximum()))
            iScrollArea->HandleScrollEvent(e);
    	else if (scrollBar)
    	{
            setEditFocus(true);
            QTextBrowser::keyPressEvent(e);
    	}
    }
#else
    QTextBrowser::keyPressEvent(e);
#endif
}

void WPTextBrowser::addScrollArea(WPScrollArea* aScrollArea)
{
    iScrollArea = aScrollArea;
}
